#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <assert.h>

#define NUM 1024
#define OP 64
char LineCommand[NUM];
char* myargv[OP];
int status = 0;
int sig = 0;
int exit_code = 0;
int main()
{
    while(1){
        printf("fengqing@hostial current_path# ");
        fflush(stdout);

        char* s = fgets(LineCommand, sizeof(LineCommand)-1, stdin);
        assert(s != NULL);
        (void)s;
        LineCommand[strlen(LineCommand)-1] = 0;
        myargv[0] = strtok(LineCommand, " ");
        int i = 1;
        if(strcmp(myargv[0], "ls") == 0)
        {
            myargv[1] = (char*)"--color=auto";
            i++;
        }
        while(myargv[i++] = strtok(NULL, " "));

        if(myargv[1] != NULL && strcmp(myargv[0], "cd")==0)
        {
            chdir(myargv[1]);
            continue;
        }

        if(myargv[0]!=NULL && myargv[1]!=NULL && strcmp(myargv[0],"echo")==0)
        {
            if(strcmp(myargv[1],"$?")==0)
            {
                printf("exit_code = %d, sig = %d\n",exit_code,sig);
            }
            else
            {
                printf(myargv[1]);
                printf("\n");
            }
                continue;
        }

#ifdef DEBUG
        for(int i = 0; myargv[i];i++)
        {
            printf("%d, %s\n",i,myargv[i]);
        }
#endif

        pid_t pid = fork();
        assert(pid != -1);
        if(pid == 0)
        {
            execvp(myargv[0],myargv);
            exit(10);
        }
        status = 0;
        waitpid(pid,&status,0);
        exit_code = (status>>8) & 0xFF;
        sig = status&0x7F;
    }
        return 0;
}
